package sctu.edu.java.year2016.team06.liuchuanjiao.day20160612.chapter15_3;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;




/**
 * Created by LCJ on 2016/6/17.
 */
public class Progress implements ActionListener ,ChangeListener{
    JFrame frame ;
    JProgressBar progressbar;
    JLabel label;
    Timer timer;
    JButton button;

    public Progress() {
        frame = new JFrame("PROGRESS");
        frame.setBounds(800, 600, 600, 150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        Container contentpanel = frame.getContentPane();
        label = new JLabel("press the button to start", JLabel.CENTER);
        progressbar = new JProgressBar();
        progressbar.setOrientation(JProgressBar.HORIZONTAL);
        progressbar.setMinimum(0);
        progressbar.setMaximum(100);
        progressbar.setValue(0);
        progressbar.setStringPainted(true);
        progressbar.addChangeListener(this);

        progressbar.setPreferredSize(new Dimension(300, 20));

        progressbar.setBorderPainted(true);

        progressbar.setBackground(Color.GREEN);
        JPanel panel = new JPanel();
        button = new JButton("start");

        button.setForeground(Color.GREEN);

        button.addActionListener(this);

        panel.add(button);

        timer = new Timer(100, this);


        contentpanel.add(panel, BorderLayout.NORTH);

        contentpanel.add(label, BorderLayout.CENTER);

        contentpanel.add(progressbar, BorderLayout.SOUTH);


        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == button) {

            timer.start();

        }
        if (e.getSource() == timer) {

            int value = progressbar.getValue();

            if (value < 100)

                progressbar.setValue(++value);

            else {
                timer.stop();

                frame.dispose();

            }

        }
    }

    public void stateChanged(ChangeEvent e1) {

        int value = progressbar.getValue();

        if (e1.getSource() == progressbar) {

            label.setText("mission has finshed：" + Integer.toString(value) + "%");

            label.setForeground(Color.BLACK);
        }
    }

    public static void main(String[] args) {

        try {

            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (Exception e) {

            Logger.getLogger(Progress.class.getName()).log(Level.FINE, e.getMessage());

            e.printStackTrace();

        }

        new Progress();

    }
}
